package com.itheima.Demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Set;

public class DemoSelector的使用01 {
    public static void main(String[] args) throws IOException {
        //创建对象
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //绑定端口
        ssc.bind(new InetSocketAddress(1314));
        //设置非阻塞
        ssc.configureBlocking(false);
        //创建Selector选择器/多路复用器
        Selector selecotr = Selector.open();
        //注册(把accept这个方法交给Selector去管理)
        ssc.register(selecotr, SelectionKey.OP_ACCEPT);
        //如果端口被访问了,ServerSocketChannel对象就会被放在这个Set集合中
        //调用Selector等待客户端的方法
        selecotr.select();
        //如果端口被访问了,ServerSocketChannel对象就会被放在这个Set集合中
        Set<SelectionKey> set = selecotr.selectedKeys();
        //遍历集合
        for (SelectionKey key : set) {
            //获取里面ServerSocketChannel对象
            //这个方法返回的是父类引用,向下转型
            ServerSocketChannel channel = (ServerSocketChannel)key.channel();
            //获取客户端
            SocketChannel accept = channel.accept();
            //创建数组
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //读取数据
            int read = accept.read(buffer);
            //打印数据;
            System.out.println(new String(buffer.array(),0,read));
        }

    }
}
